package cn.edu.swu.miniwebsvr.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpParser {

    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();
        //TODO: [222024321072027/舒鑫]
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        // 1. 解析请求行
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()) {
            throw new IOException("Invalid request line");
        }

        String[] requestLineParts = requestLine.split(" ", 3);
        if (requestLineParts.length < 3) {
            throw new IOException("Invalid request line format");
        }

        String method = requestLineParts[0];
        String url = requestLineParts[1];

        parameter.setMethod(method);

        // 解析URL参数（修复点：使用addUrlParam添加参数）
        int queryIndex = url.indexOf('?');
        if (queryIndex != -1) {
            String path = url.substring(0, queryIndex);
            String query = url.substring(queryIndex + 1);
            parameter.setUrl(path);

            // 解析查询字符串并添加到parameter
            Map<String, String> urlParams = new HashMap<>();
            parseQueryString(query, urlParams);
            for (Map.Entry<String, String> entry : urlParams.entrySet()) {
                parameter.addUrlParam(entry.getKey(), entry.getValue()); // 正确添加参数
            }
        } else {
            parameter.setUrl(url);
        }

        // 2. 解析请求头
        String headerLine;
        while ((headerLine = reader.readLine()) != null && !headerLine.isEmpty()) {
            int colonIndex = headerLine.indexOf(':');
            if (colonIndex != -1) {
                String name = headerLine.substring(0, colonIndex).trim();
                String value = headerLine.substring(colonIndex + 1).trim();
                parameter.addHeader(name, value);
            }
        }

        // 3. 解析POST请求体（修复点：使用addBodyParam添加参数）
        if ("POST".equalsIgnoreCase(method)) {
            String contentLengthStr = parameter.getHeader("Content-Length");
            String contentType = parameter.getHeader("Content-Type");

            if (contentLengthStr != null && contentType != null) {
                try {
                    int contentLength = Integer.parseInt(contentLengthStr);
                    char[] bodyChars = new char[contentLength];
                    int bytesRead = reader.read(bodyChars, 0, contentLength);

                    if (bytesRead == contentLength) {
                        String body = new String(bodyChars);
                        if ("application/x-www-form-urlencoded".equals(contentType)) {
                            Map<String, String> bodyParams = new HashMap<>();
                            parseQueryString(body, bodyParams);
                            for (Map.Entry<String, String> entry : bodyParams.entrySet()) {
                                parameter.addBodyParam(entry.getKey(), entry.getValue()); // 正确添加参数
                            }
                        }
                    }
                } catch (NumberFormatException e) {
                    System.err.println("Invalid Content-Length value: " + contentLengthStr);
                }
            }
        }

        return parameter;
    }

    // TODO: [222024321072027/舒鑫] 可以添加辅助方法来简化字符串解析和 URL 解码
    private static void parseQueryString(String query, Map<String, String> params) {
        if (query == null || query.isEmpty()) {
            return;
        }

        String[] pairs = query.split("&");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=", 2);
            if (keyValue.length > 0) {
                String key = URLDecoder.decode(keyValue[0], StandardCharsets.UTF_8);
                String value = keyValue.length > 1 ? URLDecoder.decode(keyValue[1], StandardCharsets.UTF_8) : "";
                params.put(key, value);
            }
        }
    }
}